import React, { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import { nanoid } from 'nanoid';
import { useEditor } from '@craftjs/core';
import { Button, Tooltip, Form, Input, Modal } from 'antd';
import DraggableModal from '@/components/DraggableModal';
import DebounceWrapper from '@/components/DebounceWrapper';
import { UndoOutlined, RedoOutlined } from '@ant-design/icons';
import { updateDesignPage } from '@/services/online/onlinePage';
import styles from './index.less';

const { TextArea } = Input;
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 17 },
};
const DebounceButton = DebounceWrapper(Button);

const SaveModal = ({ actionLoading, visible, closeModal, onConfirm }) => {
  const [form] = Form.useForm();

  const handleCloseModal = () => {
    if (!actionLoading) {
      closeModal();
    }
  };

  useEffect(() => {
    if (visible) {
      if (history.location.state) {
        const { pageName, pageDescription } = history.location.state;
        form.setFieldsValue({
          pageName: pageName || '',
          pageDescription: pageDescription || '',
        });
      }
    }
  }, [visible]);

  const handleConfirm = () => {
    form.validateFields().then((values) => {
      onConfirm(values);
    });
  };

  return (
    <DraggableModal
      title="保存页面"
      visible={visible}
      onCancel={handleCloseModal}
      footer={[
        <DebounceButton key="cancel" disabled={actionLoading} onClick={handleCloseModal}>
          取消
        </DebounceButton>,
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          确定
        </DebounceButton>,
      ]}
    >
      <Form {...layout} form={form} name="page-design-save">
        <Form.Item
          name="pageName"
          label="页面名称"
          initialValue=""
          rules={[{ required: true, message: '请输入页面名称' }]}
        >
          <Input maxLength={24} placeholder="请输入页面名称" />
        </Form.Item>
        <Form.Item name="pageDescription" label="页面描述" initialValue="">
          <TextArea
            maxLength={128}
            autoSize={{ minRows: 3, maxRows: 5 }}
            placeholder="请输入页面描述"
          />
        </Form.Item>
      </Form>
    </DraggableModal>
  );
};

export default ({ loading, setLoading }) => {
  const [defaultPageId, setDefaultPageId] = useState(nanoid(32));
  const [modalVisible, setModalVisible] = useState(false);
  const { actions, canUndo, canRedo, serializedJson } = useEditor((state, query) => ({
    canUndo: query.history.canUndo(),
    canRedo: query.history.canRedo(),
    serializedJson: query.serialize(),
  }));

  useEffect(() => {
    if (history.location.state) {
      const { pageId, pageContent } = history.location.state;
      setDefaultPageId(pageId);
      setTimeout(() => {
        actions.deserialize(pageContent);
      }, 500);
    } else {
      setDefaultPageId(nanoid(32));
    }
  }, []);

  const resetEditor = useCallback(() => {
    actions.deserialize(serializedJson);
  }, [defaultPageId]);

  const handleSave = (opts) => {
    setLoading(true);
    const params = {
      ...opts,
      pageId: history.location.state?.pageId || defaultPageId,
      pageContent: serializedJson,
      status: history.location.state?.status || 'unactivated',
    };
    // console.log('提交参数：', params);
    updateDesignPage(params)
      .then(() => {
        resetEditor();
        setLoading(false);
        setModalVisible(false);
        Modal.success({
          maskClosable: true,
          okText: '前往',
          content: '页面保存成功，是否前往查看列表?',
          onCancel() {
            setDefaultPageId(nanoid(32));
          },
          onOk() {
            history.push('/online/onlinePage/onlinePageManager');
          },
        });
      })
      .catch(() => {
        setLoading(false);
      });
  };

  return (
    <>
      <div className={styles.topBarContainer}>
        <span className={styles.topBarTitle}>
          页面设计
          {history.location.state && history.location.state.pageName
            ? '（' + history.location.state.pageName + '）'
            : ''}
        </span>
        <div className={styles.historyControl}>
          <Tooltip placement="bottom" title={'撤销'}>
            <DebounceButton
              size="small"
              disabled={!canUndo}
              icon={<UndoOutlined />}
              onClick={() => {
                actions.history.undo();
              }}
            />
          </Tooltip>
          <Tooltip placement="bottom" title={'恢复'}>
            <DebounceButton
              size="small"
              disabled={!canRedo}
              icon={<RedoOutlined />}
              onClick={() => {
                actions.history.redo();
              }}
            />
          </Tooltip>
          <DebounceButton
            size="small"
            type="primary"
            onClick={() => {
              setModalVisible(true);
            }}
          >
            保存页面
          </DebounceButton>
        </div>
      </div>
      <SaveModal
        actionLoading={loading}
        visible={modalVisible}
        closeModal={() => {
          setModalVisible(false);
        }}
        onConfirm={handleSave}
      />
    </>
  );
};
